package com.xhu.water_supply.web.controller;

import cn.hutool.crypto.SecureUtil;
import cn.hutool.json.JSONUtil;
import com.nimbusds.jose.JOSEException;
import com.xhu.water_supply.constants.Constants;
import com.xhu.water_supply.dto.LoginDTO;
import com.xhu.water_supply.dto.Result;
import com.xhu.water_supply.dto.ResultEnum;
import com.xhu.water_supply.dto.ResultUtils;
import com.xhu.water_supply.entity.Administrator;
import com.xhu.water_supply.service.AdministratorService;
import com.xhu.water_supply.web.exception.JwtExpiredException;
import com.xhu.water_supply.web.exception.JwtInvalidException;
import com.xhu.water_supply.web.utils.JwtComponent;
import com.xhu.water_supply.web.utils.PayloadDTO;
import com.xhu.water_supply.web.utils.ResourcesVerComponents;
import com.xhu.water_supply.web.vo.LoginVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.text.ParseException;
import java.util.Objects;

@CrossOrigin
@RestController
@Api(tags = "用户控制器")
@RequestMapping("api/administrator")
public class AdministratorController {
    @Autowired
    private AdministratorService administratorService;

    @Autowired
    private JwtComponent jwtComponent;

    @Autowired
    ResourcesVerComponents resourcesVerComponents;

    @ApiOperation(value = "用户登录接口")
    @PostMapping("login")
    public Result<LoginVO> login(LoginDTO loginDTO) throws ParseException, JOSEException {
        //1. 验证 传入的验证码是否有效
        try {
            PayloadDTO payloadDTO = jwtComponent.verifyTokenByHmac(loginDTO.getCodeUid(), Constants.JWT_SECRET_LOGIN);
            if(!loginDTO.getCode().equalsIgnoreCase(payloadDTO.getSub())){
                return ResultUtils.returnResult(ResultEnum.FAIL_VERIFY);
            }
        } catch (JwtInvalidException e) {
            return ResultUtils.returnResult(ResultEnum.FAIL_TOKEN_VERIFY);
        } catch (JwtExpiredException e) {
            return ResultUtils.returnResult(ResultEnum.FAIL_TOKEN_EXP);
        }
        //2. 验证账号密码是否正确
        Administrator loginUser = administratorService.getByLoginAccount(loginDTO.getAccount());
        if(Objects.isNull(loginUser))
            return ResultUtils.returnResult(ResultEnum.FAIL_LOGIN);
        if(!SecureUtil.md5(loginDTO.getPassword()).equals(loginUser.getPassword())){
            return ResultUtils.returnResult(ResultEnum.FAIL_LOGIN);
        }
        //3. 生成登录成功后的身份令牌,知道是登录的状态
        String jsonStr = JSONUtil.toJsonStr(loginUser);
        PayloadDTO loginPayload = jwtComponent.getDefaultPayloadDTO(jsonStr, loginUser.getAccount(), null);
        String token = jwtComponent.generateTokenByHmac(loginPayload, Constants.JWT_SECRET);
        //token保存在redis中，验证的时候从redis获取
        //4. 构建下发数据
        LoginVO loginVO = LoginVO.builder()
                .account(loginUser.getAccount())
                .name(loginUser.getName())
                .picture(resourcesVerComponents.formatImgResourceUrl(loginUser.getPicture()))
                .token(token).build();
        return ResultUtils.returnDataSuccess(loginVO);
    }


//    @Autowired
//    private AdministratorMapper administratorMapper;
//
//    @ApiOperation(value = "根据ID获取用户的信息", httpMethod = "GET", notes = "这里是Notes")
//    @ApiImplicitParams({
//            @ApiImplicitParam(name = "id", value = "用户编号", required = true)
//    })
//    @GetMapping("getById")
//    public Result<Administrator> getUser(String id){
//        Administrator administrator = new Administrator();
//        administrator.setId(id);
//        //根据id搜索
//        administrator = administratorMapper.selectOne(administrator);
//        if(Objects.isNull(administrator)){
//            return ResultUtils.returnFail("查无此人！");
//        }
//        return ResultUtils.returnDataSuccess(administrator);
//    }
}
